package com.item.read.util;

import com.alibaba.fastjson.JSONArray;
import com.google.api.Http;
import org.jdom.xpath.jaxen.JaxenXPathFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.seimicrawler.xpath.JXDocument;
import org.seimicrawler.xpath.JXNode;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class JsoupHelp {

    private static Map<String,BookSourceVo> cacheBookSourceMap = null;

    static{
        try{
            cacheBookSourceMap = new HashMap<>();

            String content = InputReadUtils.readString(JsoupHelp.class.getResourceAsStream("/bookSource.json"));
            JSONArray jsonArray = JSONArray.parseArray(content);
            if(jsonArray!=null && jsonArray.size()>0){
                for(int i = 0 ; i < jsonArray.size(); i++){
                    BookSourceVo vo = jsonArray.getJSONObject(i).toJavaObject(JsoupHelp.BookSourceVo.class);
                    cacheBookSourceMap.put(vo.getBookUrl(),vo);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Map<String,List<String>> init(String url) throws IOException {
       // String chapterUrl = "https://www.qbiqu.com/0_1"; //目录
        //String contentUrl = "/0_1"; //章节匹配

        BookSourceVo vo = getUrlBookSource(url);

        Map<String,List<String>> res = new HashMap<>();

        Element body = Jsoup.connect(url).timeout(40000).get().body();
        Elements a;
        if(vo!=null){
            a = body.select(vo.getBookChapter());
        }else{
            a = body.select("a");
        }


        List<String> chapterText = new ArrayList<>();
        List<String> chapterUrl  = new ArrayList<>();

        for(int i = 0 ; i < a.size(); i++){
            String href = a.get(i).attr("href");
            chapterText.add(a.get(i).text());
            String domainName = url.substring(0,url.replace("//","").indexOf("/")+2);
            String newUrl = "";
            if(href == null || href.length() == 0) continue;

            if(href.length() >= 2 && href.charAt(0) == '/' && href.charAt(1) == '/'){
                //跳转新域名
                newUrl =  url.substring(0,url.indexOf(":")+1) + href;
            }else if(href.charAt(0) == '/'){
                //绝对路径 域名+地址
                System.out.println(domainName + href);
                newUrl+=domainName+href;
            }else {
                //相对
                // 1 book/1
                // 2 https://www.qbiqu.com/book/1
                int j = 0,k = 0;
                String[] oldUrl = url.split("/");
                String[] oldUrl2= href.split("/");
                while(j < oldUrl.length && k < oldUrl2.length){
                    if(!oldUrl[j].equals(oldUrl2[k])){
                        newUrl+=oldUrl[j]+"/";
                    }
                    j++;
                    k++;
                }
                while(href.charAt(0) == '/'){
                    href = href.substring(1);
                }
                newUrl+=href;
                System.out.println(newUrl);
            }
            chapterUrl.add(newUrl);
        }
        res.put("text",chapterText);
        res.put("url",chapterUrl);
        return res;
    }

    /**
     * 查找配置
     * @param url
     * @return
     */
    private static BookSourceVo getUrlBookSource(String url) {
        String[] urls = url.split("/");
        String tUrl = urls[0]+"/";
        for(int i = 1 ; i < urls.length;i++){
            tUrl+=urls[i];
            if(cacheBookSourceMap.get(tUrl)!=null){
                return cacheBookSourceMap.get(tUrl);
            }
            tUrl+="/";
            if(cacheBookSourceMap.get(tUrl)!=null){
                return cacheBookSourceMap.get(tUrl);
            }
        }
        return null;
    }


    public static String getText(String url,String rootDirectory){
        BookSourceVo urlBookSource = getUrlBookSource(rootDirectory);
        Element body = null;
        try {
            body = Jsoup.connect(url).timeout(40000).get().body();
            if(urlBookSource!=null){
                body.select(urlBookSource.getBookContent());
            }
            return body.text();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static class BookSourceVo implements Serializable {
        private String name;
        private String bookUrl;
        private String bookChapter;
        private String bookContent;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getBookUrl() {
            return bookUrl;
        }

        public void setBookUrl(String bookUrl) {
            this.bookUrl = bookUrl;
        }

        public String getBookChapter() {
            return bookChapter;
        }

        public void setBookChapter(String bookChapter) {
            this.bookChapter = bookChapter;
        }

        public String getBookContent() {
            return bookContent;
        }

        public void setBookContent(String bookContent) {
            this.bookContent = bookContent;
        }
    }

//    public static void main(String[] args) throws Exception {
//        BookSourceVo vo = getUrlBookSource("https://book.qidian.com/info/1030052039/#Catalog");
//
//
//        Element body = Jsoup.connect("https://read.qidian.com/chapter/EdRT-1S4qPXywypLIF-xfQ2/0ufQk_0GjuW2uJcMpdsVgA2/").get().body();
//
//        Elements chapter = body.select(vo.getBookChapter());
//        // body.select(vo.getBookContent());
//        for(int i =0; i < chapter.size();i++){
//            System.out.println(chapter.get(i).html());
//        };
//    }



    public static void main(String[] args) {
        String data = HttpUtils.get("https://gitee.com/dulinzhi/simple-read/raw/master/src/main/resources/bookSource.json");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(JsoupHelp.class.getResource("/bookSource.json").getPath());
            fileOutputStream.write(data.getBytes(StandardCharsets.UTF_8));
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
